<?php 

require 'config/dbconfig.php';

//Check to see if user is already in the contest
@session_start();
$image = $_FILES['file']['tmp_name'];
$user = $_SESSION['id'];
$challenge_id = $_POST['challenge_id'];
$description = $_POST['description'];

$query = "SELECT * FROM contestants WHERE contestant_user_id='$user' AND contestant_challenge_id='$challenge_id' ";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) )
{
    //USER ALREADY VOTED
	exit("You already voted for this contest!");
}



//set to desired max width and max height
$max_height = 800;
$max_width = 600;
   

//saves the image in the img/contestants directory as the user id underscore challenge id .jpeg 
$new_filepath = "img/contestants/$user" . "_$challenge_id.jpeg";
echo $new_filepath; 
 
//Function to resize if image is greater than max width/height	
function resize($image, $max_width, $max_height, $width, $height, $new_filepath) {
	$img = new Imagick($image);
	//Convert to jpeg
	$img->setImageFormat('jpeg');
	//Resize if necessary
	if ($width > $max_width || $height > $max_height) {
		$img->thumbnailImage($max_width, $max_height, TRUE);
	}
	echo $challenge_id;
	$img->writeImage($new_filepath);

}

//Gets the uploaded image size, calls the resize function
list($width, $height) = getimagesize($image);
resize($image, $max_width, $max_height, $width, $height, $new_filepath);

//insert the submission into the database
$query = mysql_query("INSERT INTO contestants (contestant_user_id, contestant_challenge_id, image, description) VALUES ('$user', '$challenge_id', '$new_filepath', '$description')") or die(mysql_error());


?>